<template>
<div>
    <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);width:300px;height:500px;float:left">
        
         <span style="font-weight:600;font-size:18px">作业</span><br><br>
         <el-menu v-for="(work,index) in workInfor" :key="work.etc" :offset="index > 0 ? 0 : 0" style="text-align:left">
              <el-submenu index="index">
                <template slot="title">
                    <span >{{work.parentName}}</span>
                </template>
             <el-menu-item index="1-1" @click="download(work.workUrl)" >{{work.parentName}}作业下载</el-menu-item>
             
             </el-submenu>
         </el-menu>

    </div>
    <div style="width:50px;height:500px;float:left"></div>
    <!--提交作业-->
    <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);width:600px;height:500px;float:left">
    <span style="font-weight:600;font-size:18px">作业提交</span><br><br>
    
    <el-form :model="formData"  ref="formData" label-width="100px">
      <el-form-item label="所属章节"   prop="parentName" >
         <el-select v-model="formData.id" style="width:460px" clearable placeholder="请选择">
          <el-option
            v-for="item in workInfor"
            :key="item.parentName"
            :label="item.parentName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>   
      <!--视频上传-->
      <el-form-item label="上传作业" prop="discussTitle">
       <el-upload class="avatar-uploader" action="" :accept="acceptType" :http-request="beginUpload" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
         <el-progress :percentage="Number(percentage.toFixed(2))"></el-progress>
      
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="text" @click="handleClose">重 置</el-button>
      <el-button type="primary" @click="handleSubmit"
                 :loading="loading">{{loading?'提交中...':'确认提交'}}</el-button>
    </span>
    </div>
</div>
</template>


<script>
import {getCookie} from '@/libs/cookie'
import {select} from '@/api/modules/coursevideo'
import {selectwork} from '@/api/modules/work'
import OSS from 'ali-oss'
import {add} from "@/api/modules/student_work";

var upurl = ''
export default {
    name:'study_homework',
     props:{
             // 文件上传的接受的类型  video/* :视频类型， image/*：图片，根据需要判断
            acceptType:{
                type: String,
                default: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'   
            },
        },
    data(){
        return{
        imageUrl: '',
        percentage: 0,
        checkpoint: null,
        client: null,
        filename: '',
        upurl: '',

        loading: false,
        username:'',
        workInfor:[],
        courseID:{
            id:''
        },
         formData: {
          id:'',
          userId:'',
          courseId:'',
          nickname:'',
          workUrl:'',
          parentName:'',
          score:0
        },
        loading: false,
         options:[],
         rules: {
          parentName: [
            {required: true, message: "所属章节不能为空", trigger: "blur"}
          ],

        },
         refresh: false,
        message:{
          msg1:'设置成功',
          msg2:'作业不能为空',
          msg3:'所属章节不能为空',

        },
        }
    },
    mounted(){
        let courseID = JSON.parse(getCookie("courseID") || '{}');
        this.courseID.id = courseID
        this.formData.courseId = courseID
        let user = JSON.parse(getCookie("user") || '{}');
        this.formData.nickname = user.nickname
        this.formData.userId = user.id
        console.log(courseID)
        this.courseWork()   
    },
     created() {
            this.client = new OSS({
                region: 'oss-cn-hangzhou',
                accessKeyId: 'LTAI4GGkWMN9SyN1AkRK6qCT',
                accessKeySecret: 'sQf4RnuvZM47hXV5XxBazZqyXzJyNU',
                bucket: '0628',
                secure: false
            })
        },
    methods:{
         courseWork(filter){
            filter = {
                ...filter,
                ...this.courseID,
            }
            selectwork(filter).then(res => {
                 this.workInfor = res.data.workInfor
                  //console.log(res.data.workInfor)
            })
        },
        //上传作业
       
        beginUpload(file) {
            const isWord = ['application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.file.type); 
            if(!isWord) this.$message.error('文件必须是word');
            else{
                let _this = this
                let filename = file.file.name
                filename = filename.split('.')[0] + '_' + new Date().getTime() + '.' + filename.split('.')[1]
                _this.file = file
                _this.filename = filename
                _this.ossUpload(filename, file.file)
                //保存上传的文件下载地址
                upurl = this.client.signatureUrl(_this.filename);
                console.log(upurl)
                // location.reload();
                }
      },
          //下载文件
        download(workUrl) {
                // upurl = this.client.signatureUrl(_this.filename);
                window.location.href = workUrl;
        },
        async ossUpload(filename, file) {
                let _this = this
                try {
                    let result = await _this.client.multipartUpload(filename, file, {
                        progress: async function (p, checkpoint) {
                            _this.checkpoint = checkpoint
                            _this.percentage = p * 100
                        },
                        checkpoint: _this.checkpoint
                    })
                    console.log(result)
                } catch (e) {
                    console.log(e)
                }
            },
        handleClose() {
            this.$refs.formData.resetFields()
        },   
        handleSubmit() {
            this.$refs.formData.validate(valid => {
            if (valid) {
                this.formData.workUrl = upurl
                this.loading = true
            if(this.formData.id==''){
                 this.toast(this.message.msg3,10)
                 this.loading = false
                 this.refresh = true
            }
            else if(this.formData.workUrl==''){
                this.toast(this.message.msg2,10)
                 this.loading = false
                 this.refresh = true
            } 
            else{
              add({
                ...this.formData,
              }).then(res => {
                this.loading = false
                 console.log(res.message)
                if (res.success) {
                  this.refresh = true
                  this.toast(res.message)
                  this.handleClose()
                  
                }
              })
            }
           
          }
        })
      }
    }
}
</script>